iT邦幫忙

2023 iThome 鐵人賽

DAY 1
0
自我挑戰組

Django系列 第 19

Day19~Django 漫漫長路- RESTful method的應用

  • 分享至 

  • xImage
  •  

大家好,我是Leo
今天要來講解,django object create的幾種方式/images/emoticon/emoticon30.gif
OK~~~ Let's go now!!!


RESTful 介紹

GET 取得

用戶端使用 GET 來存取位於伺服器上指定 URL 的資源。

POST 新增

用戶端使用 POST 向伺服器傳送資料。其包含請求中的資料呈現。

PUT 修改

用戶端使用 PUT 更新伺服器上的現有資源。

DELETE 刪除

用戶端使用 DELETE 請求來移除資源。


model

假設我們今天有一張table,如下圖
https://ithelp.ithome.com.tw/upload/images/20230407/20154853JwBkReJEGi.png

from django.db import models

class Student(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255,null=True,blank=True)
    math = models.IntegerField(null=True,blank=True)
    english = models.IntegerField(null=True,blank=True)
    chinese = models.IntegerField(null=True,blank=True)
    total = models.IntegerField(null=True,blank=True)
    average = models.IntegerField(null=True,blank=True)

model/init

from .student_model import *

views

from rest_framework.response import Response
from website.models import Student
from rest_framework import permissions, views
from website.serializers import StudentSerializer
import json

class StudentAPIView(views.APIView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = []

    def get(self,request):
        #params
        name = request.GET.get('name', None)
        student = Student.objects.all()
        if name:
            # 模糊比對名字 中文+英文 不論大小寫
            student = student.filter(name__icontains=name)
        list_serializer = StudentSerializer(student, many=True)
        return Response(list_serializer.data)

    def post(self, request):
        name = request.data.get('name')
        math = request.data.get('math')
        english = request.data.get('english')
        chinese = request.data.get('chinese')

        dic = dict()
        total = []
        if math and (math != json.dumps(None)):
            dic['math'] = int(math)
            total.append(int(math))
        if english and (english != json.dumps(None)):
            dic['english'] = int(english)
            total.append(int(english))
        if chinese and (chinese != json.dumps(None)):
            dic['chinese'] = int(chinese)
            total.append(int(chinese))
        if name and (name != json.dumps(None)):
            dic['name'] = name
        dic['total'] = sum(total)
        dic['average'] = sum(total) / len(total)

        obj,created = Student.objects.update_or_create(
            pk=request.data.get('id'),
            defaults=dic
        )
        msg = 'create' if created else 'update'
        return Response({"massage": True, "msg": msg}, status=201)

    def put(self, request, id):
        student = Student.objects.filter(id=id)

        math = request.data.get('math')
        english = request.data.get('english')
        chinese = request.data.get('chinese')
        if math and (math != json.dumps(None)):
            student.update(math=int(math))
        if english and (english != json.dumps(None)):
            student.update(english=int(english))
        if chinese and (chinese != json.dumps(None)):
            student.update(chinese=int(chinese))

        total_list = student.values_list('math','chinese','english')[0]
        # drop None
        total = sum(filter(None, total_list))
        avg = total / len(total_list)
        student.update(total=total,average=avg)
        return Response({"massage": True, "msg": "update"}, status=201)

    def delete(self, request, id):
        Student.objects.filter(id=id).delete()
        return Response({"massage": True, "msg": "delete"}, status=201)

views/init

from .student import *

urls

path('api/student',StudentAPIView.as_view(),name='api-student'),
path('api/student/<int:id>/',StudentAPIView.as_view(),name='api-student-delete_put'),

postman test

  • first 先新增幾筆資料
  • get測試不比對與模糊比對結果
http://127.0.0.1:8000/api/student

資料如下
[
    {
        "id": 1,
        "name": "a",
        "math": 90,
        "english": 86,
        "chinese": 65,
        "total": 241,
        "average": 80
    },
    {
        "id": 2,
        "name": "ab",
        "math": 99,
        "english": 50,
        "chinese": 80,
        "total": 229,
        "average": 76
    },
    {
        "id": 3,
        "name": "c",
        "math": 99,
        "english": 80,
        "chinese": 57,
        "total": 236,
        "average": 78
    },
    {
        "id": 4,
        "name": "d",
        "math": 66,
        "english": 88,
        "chinese": 77,
        "total": 231,
        "average": 77
    }
]

like name = 'a%'

http://127.0.0.1:8000/api/student?name=a

資料如下
[
    {
        "id": 1,
        "name": "a",
        "math": 90,
        "english": 86,
        "chinese": 65,
        "total": 241,
        "average": 80
    },
    {
        "id": 2,
        "name": "ab",
        "math": 99,
        "english": 50,
        "chinese": 80,
        "total": 229,
        "average": 76
    }
]
  • put 修改資料 id = 1
math = 30
english = 30
http://127.0.0.1:8000/api/student/1/

資料如下
{
    "id": 1,
    "name": "a",
    "math": 30,
    "english": 30,
    "chinese": 65,
    "total": 125,
    "average": 41
}
  • delete資料 id = 4
http://127.0.0.1:8000/api/student/4/

資料如下
[
    {
        "id": 1,
        "name": "a",
        "math": 30,
        "english": 30,
        "chinese": 65,
        "total": 125,
        "average": 41
    },
    {
        "id": 2,
        "name": "ab",
        "math": 99,
        "english": 50,
        "chinese": 80,
        "total": 229,
        "average": 76
    },
    {
        "id": 3,
        "name": "c",
        "math": 99,
        "english": 80,
        "chinese": 57,
        "total": 236,
        "average": 78
    }
]

今天主要是講解method的使用方式,遵照restful風格,一個class內可以寫多個methods,明天我們來講解如何用django做排程
我們明天見,各位掰掰~~~/images/emoticon/emoticon29.gif


上一篇
Day18~Django 漫漫長路-objects create資料創建必備技能
下一篇
Day20~Django 漫漫長路- 油條配豆漿,Celery配Redis part1
系列文
Django30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言